package com.liuxm.es.test;

import cn.hutool.json.JSONUtil;
import com.liuxm.es.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
 * @author liuxm
 * @version 1.0
 * @date 2021/3/19 20:32
 */
public class DocumentPage {

    RestHighLevelClient client;

    @Before
    public void before() {
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.31.11", 9200, "http")
                )
        );
    }

    @After
    public void after() throws IOException {
        client.close();
    }

    @Test
    public void page() throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        int page = 1;
        int size = 2;
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.sort("age", SortOrder.DESC);
        sourceBuilder.sort("gender", SortOrder.ASC);
        sourceBuilder.from((page - 1) * size);
        sourceBuilder.size(size);

        showResult(sourceBuilder);

    }

    private void showResult(SearchSourceBuilder sourceBuilder) throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = searchResponse.getHits();
        long total = searchHits.getTotalHits().value;
        for (SearchHit doc : searchHits.getHits()) {
            User user = JSONUtil.toBean(doc.getSourceAsString(), User.class);
            System.out.println(user);
        }
        System.out.println("总数：" + total);
    }
}
